library(flowCore)
library(flowStats)
library(flowViz)
library(ggplot2)
library(lessR)
##install.packages("gridExtra")
library(gridExtra)
##library(multicore)

root<-"/space/alpha/dev/FACS/"
data.dir<-paste(root, "121113_2step_casa", sep="")
setwd(root)

file.names<-dir(data.dir, pattern="[0-9]$")

x<-list()
for(i in 1:length(file.names)){
  x[[i]] <- read.FCS(paste(data.dir, "/", file.names[i], sep=""), transformation=FALSE)  
}
wf<-flowSet(x)

adata<-data.frame(media=c(rep("2step", 8), rep("casa", 8)), 
                  strain=c(rep("Celedx16", 4), rep("pPRO", 4), rep("Celedx15", 4), rep("pPRO", 4)), 
                  substrate=rep(c("none", "pNP", "pNPG2", "pNPG3"),4))
mData <- data.frame(labelDescription=c("media", "strain", "substrate"))

annod<-AnnotatedDataFrame()
##pData(wf)$name<-adata$media
##pData(wf)$strain<-adata$strain
##pData(wf)$substrate<-adata$substrate
##varLabels(wf)[1]<-"media"


par(ps=28, mfrow=c(1,2))
##for(i in 1:4){
  xx<-exprs(wf[[4]])
  plot(xx[,"FSC-H"], xx[,"SSC-H"], pch=19, col="#00000022", xlab="FSC", ylab="SSC")
  gate.fsc<-c(500,700)
  gate.ssc<-c(420,600)
  idx<-which(xx[,"FSC-H"]>=gate.fsc[1] & xx[,"FSC-H"]<=gate.fsc[2] & xx[,"SSC-H"]>=gate.ssc[1] & xx[,"SSC-H"]<=gate.ssc[2])
  points(xx[idx,"FSC-H"], xx[idx,"SSC-H"], pch=19, col="#0000ff22")
  abline(v=gate.fsc[1], col="blue", lwd=2, lty=2)
  abline(v=gate.fsc[2], col="blue", lwd=2, lty=2)
  abline(h=gate.ssc[1], col="blue", lwd=2, lty=2)
  abline(h=gate.ssc[2], col="blue", lwd=2, lty=2)
  ##text(200, 1000, paste("FSC:", gate.fsc[1], "/", gate.fsc[2], sep=""))
  ##text(200, 900, paste("FSC:", gate.ssc[1], "/", gate.ssc[2], sep=""))
  length(idx)
  
  xxx<-density(xx[idx,"FL1-H"])
  plot(xxx, main="", xlim=c(-150, 700))
  polygon(xxx, col="#0000ff22", border="blue", main="")
  text(10, 0.004, c(paste("Mean:", round(mean(xx[idx,"FL1-H"]),1), sep="")))
  text(0, 0.0045, c(paste("Median:", round(median(xx[idx,"FL1-H"]),1), sep="")))
  text(30, 0.0040, paste("SD:", round(sd(xx[idx,"FL1-H"]),1), sep=""))
  abline(v=mean(xx[idx,"FL1-H"]), col="red", lwd=4, lty=2)
  abline(v=median(xx[idx,"FL1-H"]), col="blue", lwd=4, lty=2)
##}












hist(xx, freq = T, col = "grey")



## population
n=1000000
yy<-rnorm(n, mean=400, sd=1)
##yyy<-density(yy)
hist(yy, breaks=500, xlab="FL1-H", ylab="Count", main="")
##plot(yyy, xlab="FL1-H", ylab="Count", main="")
##hist

## sample
xx<-sample(yy, 100)
hist(xx, breaks=20, xlab="FL1-H", ylab="Count", main="", ps=20)














wf <- workFlow(ITN)
asinh <- arcsinhTransform()
tl <- transformList(colnames(ITN)[3:7], asinh, transformationId = "asinh")
add(wf, tl)


lg <- lymphGate(Data(wf[["asinh"]]), channels=c("SSC", "CD3"), preselection="CD4", filterId="TCells", eval=FALSE, scale=2.5)
add(wf, lg$n2gate, parent="asinh")
print(xyplot(SSC ~ CD3| PatientID, wf[["TCells+"]], par.settings=list(gate=list(col="red", fill="red", alpha=0.3))))





